﻿//
// *************************************************************************************
// WP-Framework
//
// Developed by 
// Lukas Kretschmar (lkretschmar.dev@bluewin.ch)
//
// Switzerland, Copyright (c) 2012 lkretschmar
// This content is released under the MIT License (http://opensource.org/licenses/MIT).
//     
// *************************************************************************************
//
//
			

using System;
using System.Linq.Expressions;
using KretschIT.WP_Fx.Core.Extensions;
using KretschIT.WP_Fx.Core.I18n;

namespace KretschIT.WP_Fx.Core.Validation
{
    public class It
    {
        public static void IsNotNull<T>(Expression<Func<T>> argExpr)
        {
            CheckIsValid(argExpr, v => v != null, arg => new ArgumentNullException(arg));
        }

        public static void IsValid<T>(Expression<Func<T>> argExpr, Func<T, bool> condition)
        {
            CheckIsValid(argExpr, condition);
        }

        private static void CheckIsValid<T>(Expression<Func<T>> argExpr, Func<T, bool> condition, Func<string, Exception> exception = null)
        {
            Validate(argExpr, condition);
            Check(condition, argExpr, exception);
        }
        
        private static void Validate<T>(Expression<Func<T>> argExpr, Func<T, bool> condition)
        {
            if (argExpr == null)
            {
                throw new ArgumentNullException("argExpr");
            }
            if (condition == null)
            {
                throw new ArgumentNullException("condition");
            }
        }

        private static void Check<T>(Func<T, bool> condition, Expression<Func<T>> argExpr, Func<string, Exception> exception)
        {
            var value = argExpr.Execute();
            if (!condition(value))
            {               
                Throw(exception, argExpr);
            }
        }
        
        #region Throw

        private static void Throw<T>(Func<string, Exception> exception, Expression<Func<T>> argExpr)
        {
            var argName = GetName<T>(argExpr);
            exception = GetException(exception);
            throw exception(argName);
        }
        
        private static Func<string, Exception> GetException(Func<string, Exception> exception)
        {
            if (exception == null)
            {
                exception = (arg => new ArgumentException(Messages.Exception_ArgumentConditionMissmatch, arg));
            }
            return exception;
        }

        private static string GetName<T>(Expression<Func<T>> argExpr)
        {
            var parameter = argExpr.To<MemberExpression>().Member.Name;
            return parameter;
        }

        #endregion
    }
}
